/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.jelly.tags.bsf;

import org.apache.bsf.BSFEngine;
import org.apache.bsf.BSFException;
import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Tag;
import org.apache.commons.jelly.tags.core.CoreTagLibrary;
import org.xml.sax.Attributes;

/** Describes the Taglib. This class could be generated by XDoclet
  */
public class BSFTagLibrary extends CoreTagLibrary {

    private final BSFExpressionFactory expressionFactory = new BSFExpressionFactory();

    public BSFTagLibrary() {
        registerTagFactory(
            "script",
            this::createScriptTag
            );
    }

    public BSFTagLibrary(final String language) {
        this();
        setLanguage(language);
    }

    /**
     * Factory method to create a new ScriptTag with a BSFEngine
     *
     * @param name is the name of the tag (typically 'script')
     * @param attributes the attributes of the tag
     * @return Tag
     */
    protected Tag createScriptTag(final String name, final Attributes attributes) throws JellyException {
        try {
            return new ScriptTag( expressionFactory.getBSFEngine(),
                                  expressionFactory.getBSFManager());
        }
        catch (final BSFException e) {
            throw new JellyException("Failed to create BSFEngine: " + e, e);
        }
    }

    protected BSFEngine getBSFEngine() throws BSFException {
        return expressionFactory.getBSFEngine();
    }

    public void setLanguage(final String language) {
        expressionFactory.setLanguage(language);
    }
}
